package com.edu.demo.socket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.edu.demo.entity.UsersInfo;
import com.edu.demo.service.IUsersInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/*
 *
 *   @Author: Sjy
 *   @Date: 2024/3/25-03-25-19:05
 *   用于建立长连接的类
 */
@Component
//定义此类是WS的服务器端
@ServerEndpoint("/live/gift/{username}")
public class GiftWebSocketServer {

    //ws一共有四种状态
    private static Map<String,Session> map = new HashMap<>();

    /**
     * 连接建立成功时触发
     * @param session 当前会话
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username")String username){
        map.put(System.currentTimeMillis()+username,session);
        System.out.println(username+"成功的建立了连接");
    }
    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose(@PathParam("userId")String userId){

    }
    /**
     * 收到客户端消息时触发
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        JSONObject jsonObject = new JSONUtil().parseObj(message);
        String gift = jsonObject.getStr("gift");
        String username = jsonObject.getStr("username");
        JSONObject msg = JSONUtil.createObj()
                .put("username", username)
                .put("gift", gift);
        Set set = map.keySet();
        for (Object o : set) {
            try {
                map.get(o).getBasicRemote().sendText(msg.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
    /**
     * 发生错误时触发
     * @param error
     */
    @OnError
    public void onError(Throwable error,@PathParam("userId")String userId){
        map.remove(userId);
    }
}
